<?php
  // no direct access
  defined( '_JEXEC' ) or die( 'Restricted access' );
  jimport('joomla.application.component.controller');
  
  class TeamsController extends JController
  {  
    function display(){
      
      $document =& JFactory::getDocument();
      $view = & $this->getView($this->_name, $document->getType());
      
      $division   = $this->getModel('division', 'divisionmodel');
      $conference = $this->getModel('conference', 'conferencemodel');
      
      $division_conference = $this->getModel('divisionconference', 'divisionconferencemodel');
      $conference_team     = $this->getModel('conferenceteam', 'conferenceteammodel');
      
      $divisions = $division->get();
      
      for($i=0; $i<count($divisions); $i++){
      
        $d  = $divisions[$i];
        $dcs = $division_conference->get_by_division_id($d->id);
        
        if(!isset($divisions[$i]->conferences))
          $divisions[$i]->conferences = array();
          
        if($dcs){
        
          foreach($dcs as $dc){
            $c        = $conference->get($dc->conference_id);
            $c->teams = $conference_team->get_teams_by_conference_id($dc->conference_id);
            array_push($divisions[$i]->conferences, $c);
          }
          
        }
      }
      
      /*
        Deviation: Division->conferences
      */
      $view->assign("divisions", $divisions);
      $view->display();
    }    
    
    function display_team(){
      
      $document =& JFactory::getDocument();
      $view = & $this->getView($this->_name, $document->getType());  
      
      $mteam     = $this->getModel('team', 'teammodel');
      $pic       = $this->getModel('pic', 'picmodel');
      $season    = $this->getModel('season', 'seasonmodel');
      $division  = $this->getModel('division', 'divisionmodel');
      
      $id = JRequest::getVar('id');
      if($id){
        $team       = $mteam->get($id);
        if($team->logo_id)
          $team->logo = $pic->get($team->logo_id);
        if($team->pic_id)
          $team->pic  = $pic->get($team->pic_id);
          
        $seasons    = array();
        
        $players = $this->get_players($id);
        $team->team_game_stats['HME']     = $this->get_team_stats($players);        
        $opponent_schedules = $this->get_opponent_schedules($team->id);
        $team->team_game_stats['OPP']     = $this->get_opponent_stats($opponent_schedules);
        $team->team_game_stats['DIFF']    = $this->get_stats_diff($team->team_game_stats['HME'],
                                                               $team->team_game_stats['OPP']);
        $team->history = $this->get_team_history($players);
        $view->assign("season", $season->get_latest());
        $view->assign("team", $team);
        
        #teams
        $teams = array();
        foreach($mteam->get() as $team)
          $teams[$team->id] = $team;
        
        $view->assign("teams", $teams);
        $view->assign("players", $players);
        $view->assign("divisions", $division->get());
      }
      
      $view->display_team();
    }
    
    function compare_teams(){
      
      $document =& JFactory::getDocument();
      $view = & $this->getView($this->_name, $document->getType());  
      
      $season   = $this->getModel('season', 'seasonmodel');
      $team     = $this->getModel('team', 'teammodel');
      $pic      = $this->getModel('pic', 'picmodel');
      $division = $this->getModel('division', 'divisionmodel');
      
      $id       = JRequest::getVar('id');
      $other_id = JRequest::getVar('others');
      
      $hometeam = $team->get($id);
      $awayteam = $team->get($other_id);
      if($hometeam->logo_id)
        $hometeam->logo = $pic->get($hometeam->logo_id);
      if($awayteam->logo_id)
        $awayteam->logo = $pic->get($awayteam->logo_id);
      
      $view->assign("hometeam", $hometeam);
      $view->assign("awayteam", $awayteam);
      
      $home     = array();
      $away     = array();
          
      // FOR HOME
      $players = $this->get_players($id);
      $home['HME']  = $this->get_team_stats($players);        
      $opponent_schedules   = $this->get_opponent_schedules($id);
      $home['OPP']  = $this->get_opponent_stats($opponent_schedules);
      $home['DIFF'] = $this->get_stats_diff($home['HME'],
                          $home['OPP']);
      
      // FOR AWAY
      $players = $this->get_players($other_id);
      $away['HME']  = $this->get_team_stats($players);        
      $opponent_schedules   = $this->get_opponent_schedules($other_id);
      $away['OPP']  = $this->get_opponent_stats($opponent_schedules);
      $away['DIFF'] = $this->get_stats_diff($away['HME'],
                          $away['OPP']);

      $view->assign("home", $home);
      $view->assign("away", $away);
      $view->assign("divisions", $division->get());
      
      $view->display_compare();
    }
    
    private function get_stats_diff($hme, $opp){
    
      $result = array();
      foreach($hme as $key=>$value)
        $result[$key] = abs($value - $opp[$key]);
      
      return $result;
    }
    
    private function get_players($team_id){
    
      $result           = array();
      $player           = $this->getModel('player', 'playermodel');
      $player_game_stat = $this->getModel('playergamestat', 'playergamestatmodel');
      $season           = $this->getModel('season', 'seasonmodel');
      $person           = $this->getModel('person', 'personmodel');
      
      $current_season = $season->get_latest();
      $players = $player->get_by_team_id($team_id);
      
	  if(empty($players))
	    return $result;

	  foreach($players as $p){
      
        $p->fullname = $person->get_fullname($p->person_id);
        //get stats
        $pgs   = $player_game_stat->get_season_stats_by_player_id($p->id, $current_season->id);
        $schedules = array();
        
        if($pgs){
          foreach($pgs as $stat){
            $schedules[$stat->schedule_id] = $stat;
            $categories = array("points", "off_rebounds", "def_rebounds", 
                      "assists", "steals", "blocks",
                      "field_goals", "three_points", "free_throws");
            foreach($categories as $key)
              $p->$key += $stat->$key;    
          }
        }
        
        //games played
        $p->gp = count(array_unique(array_keys($schedules)));
        //games history
        $p->history = $schedules;
        array_push($result, $p);
      }
      return $result;
    }
  
    private function get_team_stats($players){
      
      $gp = 0;
      $values = array('points' => 0, 'free_throws' => 0, 'field_goals' => 0,
                      'three_points' => 0, 'off_rebounds' => 0, 'def_rebounds' => 0,
                      'assists' => 0, 'steals' => 0, 'blocks' => 0);
              
      foreach($players as $player){
        foreach($values as $key => $value){
          if(isset($player->$key))
            $values[$key] += $player->$key;
        }
        
        if($player->gp > $gp)
          $gp = $player->gp;
      }
      
      foreach($values as $key => $value)
	    if($gp > 0)
          $values["avg_$key"] = number_format($value/$gp, 2);
		else
		  $values["avg_$key"] = 0;
      
      return $values;
    }
    
    private function get_team_history($players){
    
      $mschedule    = $this->getModel('schedule', 'schedulemodel');
      $mteam        = $this->getModel('team', 'teammodel');
      
      $result = array();
      $keys = array('points' => 0, 'free_throws' => 0, 'free_throw_attempts' => 0,
              'field_goals' => 0, 'field_goal_attempts' => 0,
                    'three_points' => 0, 'three_point_attempts' => 0,
              'off_rebounds' => 0, 'def_rebounds' => 0,
                    'assists' => 0, 'steals' => 0, 'blocks' => 0);
    
      # players
      foreach($players as $player){
        
        $history = $player->history;
        
        # history
        foreach($history as $schedule_id => $stat){
          
          if(!isset($result[$schedule_id]))
            $result[$schedule_id] = (object)$keys;
          
          foreach(array_keys($keys) as $key)
            $result[$schedule_id]->$key += $stat->$key;
          
        }
      }
      
      foreach($result as $sched_id => $values){
        $schedule = $mschedule->get($sched_id);
        $result[$sched_id]->schedule    = $schedule->schedule;
        if($schedule->first_team_id == $player->team_id)
          $result[$sched_id]->opponent_team_id = $schedule->second_team_id;
        else
          $result[$sched_id]->opponent_team_id = $schedule->first_team_id;
      }
      
      return $result;
    }
    
    private function get_opponent_schedules($team_id){
      
      $result           = array();
      $player           = $this->getModel('player','playermodel');
      $season           = $this->getModel('season', 'seasonmodel');
      $schedule         = $this->getModel('schedule', 'schedulemodel');
      
      $current_season = $season->get_latest();
      $schedules = $schedule->get_by_schedule($current_season->start_date,
                                              $current_season->end_date, $team_id);
                          
      if(!empty($schedules)){
	    foreach($schedules as $sched){
          if($sched->first_team_id == $team_id)
            $o_team_id = $sched->second_team_id;
          else
            $o_team_id = $sched->first_team_id;
        
          $result[$sched->id] = $o_team_id;
        }
	  }
      
      return $result;
    }
    
    private function get_opponent_stats($schedules){
    
      $player_game_stat = $this->getModel('playergamestat', 'playergamestatmodel');
      
      $gp = count(array_unique(array_keys($schedules)));
      $values = array('points' => 0, 'free_throws' => 0, 'field_goals' => 0,
                      'three_points' => 0, 'off_rebounds' => 0, 'def_rebounds' => 0,
                      'assists' => 0, 'steals' => 0, 'blocks' => 0);
      foreach($schedules as $schedule_id => $team_id){
      
        $stats = $player_game_stat->get_by_schedule_id($schedule_id, $team_id);
		if(!empty($stats)){
          foreach($stats as $stat){
        
            foreach($values as $key => $value)
              $values[$key] += $stat->$key;
          
          }
		}
      }
      
      foreach($values as $key => $value)
	    if($gp > 0)
          $values["avg_$key"] = number_format($value/$gp, 2);
		else
		  $values["avg_$key"] = 0;
        
      return $values;
    }
  }
?>
